﻿using UnityEngine;
using AttTypeDefine;
public class AudioMgr : MonoBehaviour {
    private static GameObject sourceObj_UI;
    private static GameObject GetUISourceObj()
    {
        if (sourceObj_UI == null)
        {
            sourceObj_UI = new GameObject
            {
                name = "UIAudioObj"
            };
            sourceObj_UI.AddComponent<AudioSource>();
            sourceObj_UI.transform.parent = Camera.main.transform;
            sourceObj_UI.transform.localPosition = Vector3.zero;
        }

        return sourceObj_UI;
    }
    public static void PlayeAudio(GameObject sourceObj, EAudioType type, string name, float volumn = -1, bool isloop = false)
    {
        string route = "";
        switch(type)
        {
            case EAudioType.Audio_Back:
                {
                    route = "Audios/BackGround/";
                    isloop = true;
                    break;
                }
            case EAudioType .Audio_CountDown :
                {
                    route = "Audios/CountDown/";
                    break;
                }
            case EAudioType.Audio_Enter :
                {
                    route = "Audios/Enter/";
                    break;
                }
            case EAudioType.Audio_Finish :
                {
                    route = "Audios/Finish/";
                    break;
                }
            case EAudioType.Audio_Keyboard:
                {
                    sourceObj = GetUISourceObj();
                    route = "Audios/Keyboard/Game";
                    break;
                }
            case EAudioType.Audio_Switch :
                {
                    route = "Audios/Switch/";
                    break;
                }
        }
        AudioClip ac = Resources.Load(route + name) as AudioClip;


        AudioSource[] srcs = sourceObj.GetComponents<AudioSource>();
        AudioSource aduioSrc = null;
        for (int i = 0; i < srcs.Length; i++)
        {
            if (!srcs[i].isPlaying)
            {
                aduioSrc = srcs[i];
            }
        }

        if (null == aduioSrc)
            aduioSrc = sourceObj.AddComponent<AudioSource>();
        if (EAudioType.Audio_Back == type)
            GlobalHelper.backGround = aduioSrc;
        aduioSrc.Stop();
        aduioSrc.loop = isloop;
        aduioSrc.clip = ac;
        aduioSrc.playOnAwake = true;
        if (volumn > 0)
            aduioSrc.volume = volumn;
        else
            aduioSrc.volume = 1f;
        aduioSrc.Play();
    }
}
